<template>
  <v-app>
    <v-container class="process-monitor" fluid>
      <!-- 标题区域 -->
      <v-row class="mb-4">
        <v-col>
          <h2 class="text-h4 font-weight-bold">{{ t('process.title') }}</h2>
          <p class="text-subtitle-1 text-medium-emphasis">{{ t('process.subtitle') }}</p>
        </v-col>
      </v-row>

      <!-- 统计信息卡片 -->
      <v-row class="mb-4">
        <v-col cols="12">
          <v-card>
            <v-card-text>
              <div class="d-flex align-center justify-space-around">
                <!-- 内存使用量 -->
                <div class="d-flex align-center">
                  <v-icon class="me-3" color="primary" size="large">{{ mdiMemory }}</v-icon>
                  <div>
                    <div class="text-h6">{{ t('process.totalMemory') }}</div>
                    <div class="text-h4 font-weight-bold">{{ totalMemory }}</div>
                  </div>
                </div>

                <!-- 分隔线 -->
                <v-divider class="mx-4" vertical></v-divider>

                <!-- CPU使用率 -->
                <div class="d-flex align-center">
                  <v-icon class="me-3" color="secondary" size="large">{{ mdiCpu64Bit }}</v-icon>
                  <div>
                    <div class="text-h6">{{ t('process.totalCpu') }}</div>
                    <div class="text-h4 font-weight-bold">{{ totalCpu }}%</div>
                  </div>
                </div>
              </div>
            </v-card-text>
          </v-card>
        </v-col>
      </v-row>

      <!-- 进程列表表格 -->
      <v-card>
        <v-card-title>
          <v-icon class="me-2">{{ mdiFormatListBulleted }}</v-icon>
          {{ t('process.processList') }}
        </v-card-title>
        <v-data-table
          class="elevation-0"
          :headers="headers"
          hide-default-footer
          :items="processItems"
          :items-per-page="-1"
          :loading="loading"
        >
          <template #item="{ item, index }">
            <tr>
              <!-- 序号列 -->
              <td class="text-caption">{{ index + 1 }}</td>

              <!-- 类型列 -->
              <td>
                <v-chip :color="getProcessTypeColor(item.type)" size="small" variant="tonal">
                  {{ t(`process.types.${item.type.toLowerCase()}`) }}
                </v-chip>
              </td>

              <!-- 名称列 -->
              <td>
                <div
                  v-if="item.name"
                  class="text-truncate"
                  style="max-width: 150px"
                  :title="item.name"
                >
                  {{ item.name || t('process.noName') }}
                </div>
              </td>

              <!-- 内存列 -->
              <td>
                <span class="font-weight-medium">{{ item.memory }}</span>
              </td>

              <!-- CPU列 -->
              <td>
                <div class="d-flex align-center">
                  <v-progress-linear
                    class="me-2"
                    :color="getCpuColor(parseFloat(item.cpu))"
                    height="6"
                    :model-value="parseFloat(item.cpu)"
                    style="min-width: 60px"
                  ></v-progress-linear>
                  <span class="text-caption">{{ item.cpu }}%</span>
                </div>
              </td>

              <!-- PID列 -->
              <td>
                <v-chip class="font-mono text-caption" size="small" variant="outlined">
                  {{ item.pid }}
                </v-chip>
              </td>
            </tr>
          </template>
        </v-data-table>
      </v-card>
    </v-container>
  </v-app>
</template>

<script lang="ts" setup>
import type { Process } from '~types/common'
import { mdiCpu64Bit, mdiFormatListBulleted, mdiMemory } from '@mdi/js'
import { computed, onUnmounted, ref } from 'vue'
import { useSystemStateListener } from '@/composables/useSystemStateListener'
import { useI18n } from 'vue-i18n'

// 启动系统状态监听器
useSystemStateListener()
const { t } = useI18n()

// 响应式数据
const pros = ref<Process[]>([])
const totalMemory = ref<string>('')
const totalCpu = ref<string>('')
const loading = ref<boolean>(true)

// 表格头部配置
const headers = computed(() => [
  {
    title: t('process.headers.index'),
    key: 'index',
    sortable: false,
    width: '80px'
  },
  {
    title: t('process.headers.type'),
    key: 'type',
    sortable: true,
    width: '120px'
  },
  {
    title: t('process.headers.name'),
    key: 'name',
    sortable: true
  },
  {
    title: t('process.headers.memory'),
    key: 'memory',
    sortable: true,
    width: '120px'
  },
  {
    title: t('process.headers.cpu'),
    key: 'cpu',
    sortable: true,
    width: '150px'
  },
  {
    title: t('process.headers.pid'),
    key: 'pid',
    sortable: true,
    width: '100px'
  }
])

// 处理后的进程数据
const processItems = computed(() =>
  pros.value.map((process, index) => ({
    ...process,
    index
  }))
)

/**
 * 根据进程类型获取颜色
 */
function getProcessTypeColor(type: string): string {
  const colorMap: Record<string, string> = {
    Browser: 'info',
    Utility: 'success',
    GPU: 'info',
    Tab: 'warning',
    Extension: 'secondary'
  }
  return colorMap[type] || 'default'
}

/**
 * 根据CPU使用率获取颜色
 */
function getCpuColor(cpu: number): string {
  if (cpu >= 80) return 'error'
  if (cpu >= 50) return 'warning'
  if (cpu >= 20) return 'info'
  return 'success'
}

let stopMonitoring: () => void

onMounted(() => {
  // 使用新的 startMonitoring API，每秒更新一次
  stopMonitoring = _pre_.monitor.startMonitoring(data => {
    pros.value = data.process
    totalMemory.value = data.totalMemory
    totalCpu.value = data.totalCpu
    loading.value = false
  }, 1000)
})

onUnmounted(() => {
  // 停止监控
  if (stopMonitoring) {
    stopMonitoring()
  }
})
</script>

<style scoped>
.process-monitor {
  max-width: 1200px;
  margin: 0 auto;
}

.text-truncate {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 确保表格在小屏幕上的响应式 */
:deep(.v-data-table) {
  border-radius: 8px;
}

:deep(.v-data-table__wrapper) {
  border-radius: 8px;
}

/* 统计卡片样式 */
:deep(.v-card) {
  border-radius: 12px;
  transition: all 0.3s ease;
}

:deep(.v-card:hover) {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

/* 进度条样式 */
:deep(.v-progress-linear) {
  border-radius: 3px;
}

/* 等宽字体样式 */
.font-mono {
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
}
</style>

<!-- 国际化文本定义 -->
<i18n>
{
  "en": {
    "process": {
      "title": "Process Monitor",
      "subtitle": "Real-time monitoring of application processes",
      "totalMemory": "Total Memory Usage",
      "totalCpu": "Total CPU Usage",
      "processList": "Process List",
      "loading": "Loading process data...",
      "headers": {
        "index": "#",
        "type": "Type",
        "name": "Name",
        "memory": "Memory",
        "cpu": "CPU",
        "pid": "PID"
      },
      "types": {
        "browser": "Browser",
        "utility": "Utility",
        "gpu": "GPU",
        "tab": "Tab",
        "extension": "Extension"
      }
    }
  },
  "zhHans": {
    "process": {
      "title": "进程监控",
      "subtitle": "实时监控应用程序进程状态",
      "totalMemory": "总内存使用量",
      "totalCpu": "总CPU使用率",
      "processList": "进程列表",
      "loading": "正在加载进程数据...",
      "headers": {
        "index": "序号",
        "type": "类型",
        "name": "名称",
        "memory": "内存",
        "cpu": "CPU",
        "pid": "进程ID"
      },
      "types": {
        "browser": "浏览器",
        "utility": "实用工具",
        "gpu": "图形处理",
        "tab": "标签页",
        "extension": "扩展"
      }
    }
  }
}
</i18n>
